import { Component, Vue, Prop, PropSync, Watch } from 'vue-property-decorator'
import style from '@/views/AuthorizeNew/AuthorizeNew.less'
import styles from '@/views/NewApply/NewApply.less'
import { ElTable } from 'element-ui/types/table'
// import lodash from 'lodash'
import Driver from 'driver.js'
import { Action } from 'vuex-class'
import SealStatus from '@/components/SealStatus'
import { projectStatus } from '@/views/AuthorizeApp'
import { APP_INTERFACE_TYPE } from '@/views/AuthorizeApp'
import OperationCol from '@/components/OperationCol'
import TableEmpty from '@/components/tableEmpty'

@Component({})
export default class ApplicationTable extends Vue {
  private loading: boolean = false
  private appName: string = ''
  private developer: string = ''
  private projectId: string = ''
  private orgName: string = ''
  private appList: any[] = []
  private pageIndex: number = 1
  private pageSize: number = 10
  private total: number = 0
  private driver: any = null
  private cascaderProps = {
    value: 'uuid',
    label: 'fullName',
    children: 'subList',
  }
  private options = []
  private area: string = ''
  private areaOption: any[] = []
  project: any = null
  @Prop({ default: false }) private multi!: any[] // 是否多选
  @Prop({ default: false }) private showDriver!: boolean // 是否显示引导
  @Prop({ default: '' }) private sealCode!: string // 印章编码
  @Prop({ default: false }) private isAuth!: boolean // 是否授权
  @Prop({ default: '' }) emptyText!: string

  @PropSync('selection', { default: () => [] }) private selectList!: any[] // 已选择的
  @PropSync('select', { default: () => {} }) private selected!: any

  @Action('project/queryProjectSimplesBySealUseType')
  private queryProjectSimplesBySealUseType!: any

  @Action('project/queryProjectManageSealAuthorizeListBySeal')
  private queryProjectManageSealAuthorizeListBySeal!: any

  @Action('project/queryProjectSimplesBySealUseTypeBySeal')
  private queryProjectSimplesBySealUseTypeBySeal!: any

  @Action('applyPage/getAreas') private getAreas!: any
  protected render() {
    return (
      <div>
        <div class={style.content}>
          <el-form ref="elform" class="search-form">
            <div>
              <el-row>
                <el-col span={8}>
                  <el-form-item label="应用ID">
                    <el-input v-model={this.projectId} placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col span={8}>
                  <el-form-item label="应用名称">
                    <el-input v-model={this.appName} placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col span={8}>
                  <el-form-item label="应用主管单位">
                    <el-input v-model={this.orgName} placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col span={8}>
                  <el-form-item label="应用开发单位">
                    <el-input v-model={this.developer} placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col span={8}>
                  <el-form-item label="应用主管单位区域">
                    <el-cascader
                      ref="areaSelect"
                      v-model={this.areaOption}
                      placeholder="默认全部区域"
                      options={this.options}
                      // onVisible-change={this.areaOptionBlur}
                      show-all-levels={false}
                      {...{
                        props: { props: this.cascaderProps },
                      }}
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div>
              <el-form-item>
                <el-button size="mini" type="primary" onClick={this.query}>
                  搜索
                </el-button>
                <el-button size="mini" onClick={this.reset}>
                  重置
                </el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <el-table
          class={['select-check', { [style.singleTable]: !this.multi }]}
          data={this.appList}
          style="width: 100%"
          v-loading={this.loading}
          onSelect={this.selectHandle}
          onSelect-all={this.selectAllHandle}
          onRow-click={this.rowClick}
          ref="table"
        >
          <TableEmpty
            v-show={!this.loading}
            slot="empty"
            msg={
              this.sealCode
                ? this.emptyText
                : '当前查询条件下暂无可授权的云签章应用'
            }
          >
            {this.sealCode && !this.isAuth ? (
              <el-button type="primary" onClick={this.authorizeApp}>
                前往授权新应用
              </el-button>
            ) : (
              <el-button type="primary" onClick={this.toProjectList}>
                返回授权应用列表
              </el-button>
            )}
          </TableEmpty>
          {this.multi ? (
            <el-table-column
              selectable={this.selectable}
              type="selection"
              width="55"
            />
          ) : (
            <el-table-column
              width="55"
              {...{
                scopedSlots: {
                  default: (scope: any) => {
                    return (
                      <el-radio-group v-model={this.project}>
                        <el-radio label={scope.row.projectId} />
                      </el-radio-group>
                    )
                  },
                },
              }}
            />
          )}
          <el-table-column
            prop="projectId"
            label="应用ID"
            min-width="100"
            show-overflow-tooltip
          />
          <el-table-column
            prop="projectName"
            label="应用名称"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="projectOrganizeName"
            label="应用主管单位"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="developerName"
            label="应用开发单位"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="validType"
            label="对接方式"
            min-width="100"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return APP_INTERFACE_TYPE[scope.row.validType]
                },
              },
            }}
          />
          <el-table-column
            prop="sealApplyStatus"
            label="状态"
            min-width="90"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <SealStatus
                      statusData={projectStatus.find(
                        item => scope.row.status === item.key
                      )}
                    />
                  )
                },
              },
            }}
          />
          {
            <el-table-column
              prop="id"
              label="操作"
              width="200"
              {...{
                scopedSlots: {
                  default: (scope: any) => {
                    return (
                      <span>
                        <OperationCol
                          operations={this.filterOptions(scope.row)}
                          showNum={4}
                          row={scope.row}
                          index={scope.$index}
                        />
                      </span>
                    )
                  },
                },
              }}
            />
          }
        </el-table>
        {this.appList && this.appList.length > 0 && (
          <el-pagination
            class={{ [styles.pagination]: true }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pageIndex}
            page-sizes={[10, 20, 30]}
            page-size={this.pageSize}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.total}
            pager-count={5}
          />
        )}
      </div>
    )
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 1,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
      {
        id: 2,
        text: this.isAuth ? '授权' : '取消授权',
        onClick: (index: number, rows: any) => {
          this.authProject(rows)
        },
      },
    ]

    return btns
  }

  detail(row: any) {
    this.$emit('detail', row)
  }

  authProject(row: any) {
    this.$emit('auth', row)
  }

  filterOptions(row: any) {
    if (!this.sealCode) {
      return [this.getOperations[0]]
    }

    return this.getOperations
  }

  authorizeApp() {
    this.$router.push({ name: 'authorizeNew' })
  }

  toProjectList() {
    this.$router.push({ name: 'authorizeApp' })
  }

  @Watch('selectList.length')
  selectListChange(val: number) {
    this.showSelects()
  }

  @Watch('selected', { deep: true })
  selectdChange(val: any) {
    this.project = (val || { projectId: '' }).projectId
  }

  handleSizeChange(val: number) {
    this.pageIndex = 1
    this.pageSize = val
    this.queryList()
  }

  handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  async queryList() {
    this.loading = true
    const url = this.sealCode
      ? this.isAuth
        ? this.queryProjectSimplesBySealUseTypeBySeal
        : this.queryProjectManageSealAuthorizeListBySeal
      : this.queryProjectSimplesBySealUseType
    await url({
      developerName: this.developer,
      pageIndex: this.pageIndex,
      pageNumber: this.pageSize,
      projectOrganizeName: this.orgName,
      sealUseType: 2,
      projectName: this.appName,
      projectId: this.projectId,
      organizeUuid: this.area,
      sealCode: this.sealCode,
    })
      .then((res: any) => {
        this.appList = (res || {}).list || []
        this.total = res.total
      })
      .catch(() => {})
    this.showSelects()
    this.loading = false
    const table = this.$refs.table as ElTable
    table && table.doLayout()
  }

  query() {
    this.pageIndex = 1
    this.queryList()
  }

  @Watch('areaOption')
  private areaOptionChange(val: any) {
    this.area = (typeof val === 'object' ? val[val.length - 1] : val) || ''
  }

  mounted() {
    this.$nextTick(() => {
      if (this.showDriver) {
        this.driver = new Driver({
          allowClose: false,
          opacity: 0.5,
          closeBtnText: '知道了',
          className: 'authother-popover',
        })
        this.driver.highlight({
          element: '.el-table__header',
          popover: {
            title: '请选择需要同步印章的其他应用',
            description: '',
          },
        })
      }
      this.project = (this.selected || { projectId: null }).projectId
      this.getAreas().then((data: any) => {
        this.options = data
      })
      this.query()
    })
  }

  beforeDestroy() {
    // 重置
    this.driver && this.driver.reset()
  }

  reset() {
    this.appName = ''
    this.developer = ''
    this.orgName = ''
    this.projectId = ''
    this.area = ''
    this.areaOption = []
    this.query()
  }

  rowClick(row: any) {
    this.$emit('update:select', row)
  }

  selectable(row: any, index: number) {
    return (
      this.multi ||
      this.selectList.length < 1 ||
      row.projectId === (this.selectList[0] || { projectId: null }).projectId
    )
  }

  selectHandle(selection: any[], row: any) {
    if (
      this.selectList.findIndex(a => {
        return a.projectId === row.projectId
      }) < 0
    ) {
      this.$emit('selectChange', this.selectList.concat([row]))
    } else {
      const list = this.selectList
      list.splice(
        this.selectList.findIndex(a => {
          return a.projectId === row.projectId
        }),
        1
      )
      this.$emit('selectChange', list)
    }
  }

  selectAllHandle(selection: any) {
    if (!this.multi) {
      ;(this.$refs.table as ElTable) &&
        (this.$refs.table as ElTable).clearSelection()
      this.showSelects()
      this.$emit('selectChange', this.selectList)
      // }

      return
    }
    if (selection.length === 0) {
      const list = this.selectList.filter((select: any) => {
        return (
          this.appList.findIndex(a => {
            return a.projectId === select.projectId
          }) < 0
        )
      })
      this.$emit('selectChange', list)
    } else {
      const arr = this.selectList.concat(selection)
      this.$emit('selectChange', this.unique(arr))
    }
  }

  showSelects() {
    // 部门列表懒加载、tag和列表checkbox联动时同步列表的checkbox数据
    this.$nextTick(() => {
      ;(this.$refs.table as ElTable) &&
        (this.$refs.table as ElTable).clearSelection()
      this.appList.map(app => {
        if (
          this.selectList.filter(select => select.projectId === app.projectId)
            .length > 0
        ) {
          ;(this.$refs.table as ElTable) &&
            (this.$refs.table as ElTable).toggleRowSelection(app)
        }

        return app
      })
    })
  }
  unique(arr: any[]) {
    // 去重
    return arr.filter(function(item, index, arr) {
      // 当前元素，在原始数组中的第一个索引==当前索引值，否则返回当前元素
      return (
        arr.findIndex(a => {
          return a.projectId === item.projectId
        }) === index
      )
    })
  }
}
